import * as echarts from '../../../../ec-canvas/echarts';
var httpUtil = require('../../../../utils/httpUtil.js')
var uiUtil = require('../../../../utils/uiUtil.js')
var util = require('../../../../utils/util.js')
var emptyUtil = require('../../../templates/empty/empty.js')
const app = getApp()
var that, priceChatDomOrder, priceChatDomSave, priceChatDomNz

Page({

  /**
   * 页面的初始数据
   */
  data: {
    priceEc: {
      lazyLoad: true // 将 lazyLoad 设为 true 后，需要手动初始化图表
    },
    isInitEcOrder: false, //是否已初始化ECharts
    isInitEcSave: false, //是否已初始化ECharts
    isInitEcNz: false, //是否已初始化ECharts

    emptyParam: {},
    detail: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    uiUtil.showLoading("正在加载..")

    this.requestDataDetail(options);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return util.handleShareApp()
  },


  /**
   * 请求月报详情
   */
  requestDataDetail(options) {
    httpUtil.PostRequestHeaderApp("detail_app_savemoney", {
      appId: options.appid,
      recordId: options.recordid
    }, {
      success(res) {
        uiUtil.hideLoading();
        emptyUtil.hideView();
        let yearText=res.month.split("-")[0];
        let monthText = res.month.split("-")[1];
        if (monthText<10){
          monthText = monthText.split("")[1];
        }
        res.yearText = yearText;
        res.monthText = monthText;
        that.setData({
          detail:res
        })

        // 页面名称
        wx.setNavigationBarTitle({
          title: res.yearText + "年" + res.monthText+"月省钱快报"
        });

        // 获取组件
        priceChatDomOrder = that.selectComponent('#price-chart-dom-order');
        priceChatDomSave = that.selectComponent('#price-chart-dom-save');
        priceChatDomNz = that.selectComponent('#price-chart-dom-nz');
        that.initPriceChart(priceChatDomOrder, "isInitEcOrder", res.orderAmountChart, "line");
        that.initPriceChart(priceChatDomSave, "isInitEcSave", res.saveAmountChart, "line");
        that.initPriceChart(priceChatDomNz, "isInitEcNz", res.nzChart, "pie");
      },
      fail(code, res) {
        // uiUtil.showToast(res);
        uiUtil.hideLoading();
        var text = emptyUtil.getErrText(code, res, "获取数据失败")
        emptyUtil.showFailView(text);
      }
    })
  },

  /**
   * 初始化图标
   */
  initPriceChart(priceChatDom, isInitEc, priceList,seriesType) {
    if (that.data[isInitEc] || !priceChatDom || !this.data.detail) {
      return;
    }
    this.setData({
      [isInitEc]: true,
    })
    // var priceList = this.data.detail.orderAmountChart
    // if (!priceList || priceList.length == 0) {
    //   return
    // }
    priceChatDom.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      //整理横坐标，value值

      var xDatas = []
      var yValues = []
      if (seriesType=="pie"){
        yValues = priceList
      } else {
        var length = priceList.length
        for (var i = 0; i < length; i++) {
          var item = priceList[i]
          xDatas.push(item.x)
          yValues.push(item.y)
        }
      }
      setChartOption(chart, xDatas, yValues, seriesType);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
})

function setChartOption(chart, xDatas, yValues, seriesType) {
  if (seriesType == "pie"){
    var option = {
      series: [{
        type: 'pie',
        label: {
          formatter: '{b} ({d}%)'
        },
        data: yValues
      }]
    };
  } else {
    var option = {
      grid: {
        top: '10%',
        bottom: '18%',
        left:'18%',
        right:"1%"
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xDatas,
        axisLabel: {
          color: '#969696'
        },
      },
      yAxis: {
        x: 'center',
        type: 'value',
        axisLabel: {
          color: '#C6C6C6'
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: ['#D6D6D6']
          }
        },
        //   show: false
      },
      
      series: [{
        type: seriesType,
        data: yValues,
        showSymbol: true,
        symbol: 'circle', //设定为实心点
        color: ["#CFB286"], //折现颜色
        areaStyle: {
          normal: {
            opacity: 0.3,
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1, [{
                offset: 0,
                color: '#CFB286'
              },
              {
                offset: 0.3,
                color: '#CFB286'
              },
              {
                offset: 1,
                color: '#FFF'
              }
              ]
            )
          }
        },
      }]
    };
  }

  chart.setOption(option);
}